/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     http://Yi.tech
 * @date:        2019/5/20 20:57
 * @email:       https:yiyuery.github.io/NoteBooks
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.swagger.common.context;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-06-05 22:45
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-06-05
 * @modify reason: {方法名}:{原因}
 * ...
 */
public class AppBeanContext {

    private static class SingletonHolder {
        private static final AppBeanContext INSTANCE = new AppBeanContext();
    }

    public static final AppBeanContext getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static final Map<String, Object> HOLDER = new HashMap<>();

    /**
     * 注册实例
     * @param name
     * @param bean
     */
    public void registerBean(String name, Object bean) {
        if (HOLDER.containsKey(name)) {
            throw new IllegalStateException("bean repetition register!");
        }
        HOLDER.putIfAbsent(name, bean);
    }

    /**
     * 获取实例
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getBean(String name, Class<T> clazz) {
        if (!HOLDER.containsKey(name)) {
            throw new IllegalArgumentException("bean hasn't been registered!");
        }
        return clazz.cast(HOLDER.get(name));
    }
}

